package org.nowcoder.leetcode.twoPointers;

/**
 * Title  : 21. Merge Two Sorted Lists
 * Source : https://leetcode.cn/problems/merge-two-sorted-lists/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-07-12
 */

public class LeetCode_21 {

    class ListNode {
        public int val;
        public ListNode next;

        public ListNode() {
        }

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        //处理特殊情况
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        //正常拼接
        ListNode head = null, p = null;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                if (head == null) {
                    head = list1;
                } else {
                    p.next = list1;
                }
                p = list1;
                list1 = list1.next;
            } else {
                if (head == null) {
                    head = list2;
                } else {
                    p.next = list2;
                }
                p = list2;
                list2 = list2.next;
            }
        }
        //处理链表长度不一致
        ListNode list = list1;
        if (list2 != null)
            list = list2;
        while (list != null) {
            p.next = list;
            p = list;
            list = list.next;
        }
        return head;
    }
}
